<?php
/**
 * 控制器基类
 * 
 * @author by wangqiang <960875184@qq.com>
 * @date 2013-11-01
 *
 */
abstract class ControllersBase {
    protected $model;
    protected $view;
    protected $theme;
    protected $layout = 'index';
    protected $viewContent = '';
    protected $viewPrefix = '.php';
    public  $defaultAction = 'index';
    private static $_rootPath = '';

    /**
     * 构造函数
     *
     * @return void
     */
    public function __construct(){
        self::$_rootPath = ROOT_PATH;
        $this->init();
    }

    /**
     * 初始化
     *
     * @return void
     */
    protected function init() {
        $this->model = ModelsBase::getInstance();
    }
    
    /**
     * 定义请求函数 post ，get方法通用
     * 
     * @param string $name  $_POST[$name]
     * @param string $method post|get
     *
     * @return string 
     */
    protected function _request($name, $method=''){
        if (empty($method)) {
            return $_REQUEST[$name];
        }

        return strtoupper($method) == 'POST' ? $_POST[$name] : $_GET[$name];
    }

    /**
     * 拦截器
     */
    protected function interceptor($sessionName, $url, $time=0){
        if(!isset($_SESSION[$sessionName])) {
            LibsCommon::redirect($url, $time);
            print("对不起,您还没有登录,请先登录，{$time}秒之后跳转....");
            exit;
        }
    }

    /**
     *分页
     *2012-5-4
     */
    protected function setPage($data,$total_num,&$filter=array('page_size'=>20,'page'=>1)) {

        $data['total_num'] = $total_num;
        $data['page_num'] = ceil($data['total_num']/$filter['page_size']);
        $data['page'] = $filter['page'];
        $data['page_size'] = $filter['page_size'];
        if($data['page_num']==1) {
            $data['select_page']= array(1);
        }elseif($data['page_num'] < 7 && $data['page_num'] > 1) {
            for($i=1;$i<=$data['page_num'];$i++) {
                $data['select_page'][]= $i;
            }
        }elseif($data['page_num'] >= 7) {
            $data['select_page']= array(1,2,3,$data['page_num']-2,$data['page_num']-1,$data['page_num']);
        }
        $filter['page_num'] = $data['page_num'];
        $data['filter'] = $filter;

        return $data;
    }

    /**
     *json格式输出 
     *2012-5-5
     */
    protected function makeJsonExit($tpl,array $filter = array()) {
        $fileName = self::$_rootPath.DIRECTORY_SEPARATOR.'views'.DIRECTORY_SEPARATOR.$tpl;
        
        $contents = LibsCommon::fetchTpl($fileName);
        $ret = array('content'=>$contents,'filter'=>$filter);
        exit(json_encode($ret));
    }
    
    protected function addMagic($arr) {
        foreach($arr as &$value) {
            $value = trim($value);
            $value = addslashes($value);
        }
        return $arr;
    }

    /**
     * 输出结果
     *
     *
     * @return bool
     */
    final public function output($action, array $params = array()) {
        call_user_func_array(array($this, $action), $params);

        $fileName = self::$_rootPath.DIRECTORY_SEPARATOR.'views'; 
        if (empty($this->view)) {
            $fileName .= preg_replace_callback(
                '#[A-Z]#', 
                create_function('$match', 'return DIRECTORY_SEPARATOR.strtolower($match[0]);'),
                str_replace('Controllers', '', get_class($this))
            );
            $fileName .= DIRECTORY_SEPARATOR.$action.$this->viewPrefix;
        } else {
            $fileName .= DIRECTORY_SEPARATOR.$this->view.$this->viewPrefix;
        }
        if (!file_exists($fileName)) {
            throw new Exception("tpl:{$fileName} not exist!");
            return false;
        }

        ob_start();
        include $fileName;
        $this->viewContent = ob_get_contents();
        ob_end_clean();

        //加载布局
        if (!empty($this->layout)) {
            $fileName = self::$_rootPath.DIRECTORY_SEPARATOR.'layouts';
            if (!empty($this->theme)) {
                $fileName .= DIRECTORY_SEPARATOR.$this->theme;    
            }
            $fileName .= DIRECTORY_SEPARATOR.$this->layout.$this->viewPrefix;

            include $fileName;
        } else {
            echo $this->viewContent;
        }

       return true;
    }

}
